package com.core.reach.cloudhub.service.impl;

import cn.hutool.core.util.IdUtil;
import com.core.reach.cloudhub.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author ga.zhang
 * @version V1.0
 * @description: TODO
 * @date 2020/3/25 17:24
 **/
@Service("paymentService")
public class PaymentServiceImpl implements PaymentService {

    /**==============================================服务降级==============================================*/

    @Override
    public String paymentInfoOk(Long id) {
        return "线程池：" + Thread.currentThread().getName() + "\t" + "paymentInfoOk,id:" + id + "\t" + "【表情】";
    }

    /**
     * HystrixCommand注解的作用：服务降级，
     * 当服务请求时间超过HystrixProperty注解内设置的超时时间3秒后
     * 或方法报错时，
     * 自动启用发累了吧fallback方法paymentInfoTimeOutHandler
     */
    @Override
    @HystrixCommand(fallbackMethod = "paymentInfoTimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    public String paymentInfoTimeOut(Long id) {
//        int i = 10 / 0;
        int second = 3;
        try {
            TimeUnit.SECONDS.sleep(second);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + "\t" + "paymentInfoTimeOut,id:" + id + "\t" + "ㄟ(⊙ω⊙ㄟ)哈";
    }

    public String paymentInfoTimeOutHandler(Long id){
        return "线程池：" + Thread.currentThread().getName() + "\t" + "paymentInfoTimeOutHandler,id:" + id + "\t" + "ε=(･д･｀*)ﾊｧ…";
    }


    /**==============================================服务熔断==============================================*/

    /**
     * 在10秒的时间窗口期内10次请求有6次(也就是60%)是请求失败的,断路器将起作用
     * HystrixCommandProperties类中含有所有的HystrixProperty属性
     */
    @Override
    @HystrixCommand(
            fallbackMethod = "paymentCircuitBreakerFallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),// 时间窗口期/时间范围
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")// 失败率达到多少后跳闸
    }
    )
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("*****id不能是负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功,流水号:" + serialNumber;
    }

    public String paymentCircuitBreakerFallback(Integer id) {
        return "id 不能负数,请稍后重试,o(╥﹏╥)o id:" + id;
    }
}
